package cn.edu.nuc.ssm.service.impl;

import cn.edu.nuc.ssm.dao.CategoryMapper;
import cn.edu.nuc.ssm.dao.PayIncomeMapper;
import cn.edu.nuc.ssm.entity.Category;
import cn.edu.nuc.ssm.entity.PayIncome;
import cn.edu.nuc.ssm.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by Administrator on 2017/5/2.
 */
@Service
public class CategoryServiceImpl implements CategoryService{

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private PayIncomeMapper payIncomeMapper;

    public Category findByid(Integer id){

        return categoryMapper.findbyId(id);
    }

    public int updateSelective(Category category){

        return categoryMapper.updateNameById(category.getName(),category.getId());
    }

    @Transactional
    public int deleteCategoryAndRefece(Integer uid,Integer ctid){

         payIncomeMapper.deletebyCtidandUid(ctid, uid);

        int i1 = categoryMapper.deleteByPrimaryKey(ctid);
        if (i1<=0){
            throw new RuntimeException();
        }
        return i1;
    }


    public List<Category> listCategory(){

       return  categoryMapper.findSimiler();
    }

    @Override
    public int updatename(Integer id,String name) {


        return categoryMapper.updateNameById(name,id);
    }

    public int insert(Category category){

        return categoryMapper.insertSelective(category);
    }

    public List<Category> findByName(String name){

        return categoryMapper.findbyName(name);
    }

    @Transactional
    public int delete(Integer id){

        List<PayIncome> payIncomes = payIncomeMapper.findbyCtid(id);
        if (payIncomes.size()>0){

            int i1 = payIncomeMapper.deletebyCtid(id);
            if (i1<0){

                throw new RuntimeException();
            }
        }
        int i =  categoryMapper.deletebyId(id);
        if (i<0){

            throw new RuntimeException();
        }

        return 1;

    }
}
